﻿using UnityEngine;
using System.Collections;
using System;

public class JohnnyClock : MonoBehaviour {

	public Mesh[] NumberMeshes;
	public Mesh MeshA;
	public Mesh MeshP;

	public MeshFilter HoursTens;
	public MeshFilter HoursOnes;
	public MeshFilter MinutesTens;
	public MeshFilter MinutesOnes;
	public MeshFilter SecondsTens;
	public MeshFilter SecondsOnes;
	public MeshFilter AMPMHolder;

	int LastSeconds;
	DateTime CurrentDT;

	// Use this for initialization
	void Start () {
		LastSeconds = System.DateTime.Now.AddSeconds(-1).Second;
	}
	
	// Update is called once per frame
	void Update () {
		CurrentDT = DateTime.Now;
		if (CurrentDT.Second != LastSeconds) {
			int hour = CurrentDT.Hour > 12 ? CurrentDT.Hour - 12 : CurrentDT.Hour;
			if (hour == 0) hour = 12;
			int ampm = CurrentDT.ToString("tt")[0] == 'A' ? 0 : 1;
			this.HoursTens.mesh = GetNumberMesh(hour, 2);
			this.HoursOnes.mesh = GetNumberMesh(hour, 1);
			this.MinutesTens.mesh = GetNumberMesh(CurrentDT.Minute, 2);
			this.MinutesOnes.mesh = GetNumberMesh(CurrentDT.Minute, 1);
			this.SecondsTens.mesh = GetNumberMesh(CurrentDT.Second, 2);
			this.SecondsOnes.mesh = GetNumberMesh(CurrentDT.Second, 1);
			this.AMPMHolder.mesh = (ampm == 1) ? this.MeshP : this.MeshA;
			LastSeconds = CurrentDT.Second;
		}
	}

	Mesh GetNumberMesh(int number, int place) {
		int currentNumber = number % (int)Math.Pow(10,place) / ((place == 1) ? 1 : ((int)Math.Pow(10,place-1)));
		//Debug.Log(currentNumber);
		return NumberMeshes[currentNumber];
	}
}
